<?php
/**
 * Custom template tags for this theme
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package dadong2g
 */

//调试信息
function zb_dump() {
    $backtrace = debug_backtrace();
    $caller = array_shift($backtrace);

    echo PHP_EOL . '<pre class="site-zb-dump bg-dark text-warning">';
    echo '<div class="zb-dump-code">';
    foreach (func_get_args() as $arg) {
        var_dump($arg);
    }
    echo '</div>';
    printf( '<div class="zb-dump-info">%1$s from %2$s [line %3$s]</div>', wp_date('Y-m-d H:i:s'), $caller['file'], $caller['line'] );
    echo '</pre>' . PHP_EOL;
}

//获取用户客户端IP get_ip_address()
function get_ip_address($ignore_private_and_reserved = false) {
    $flags = $ignore_private_and_reserved ? (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) : 0;
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, $flags) !== false) {
                    return $ip;
                }
            }
        }
    }
    return 'unknown';
}





function zb_get_color_class($key = 0) {
    $colors  = ['danger', 'primary', 'success', 'warning', 'info', 'secondary'];
    $color   = (isset($colors[$key])) ? $colors[$key] : 'secondary';
    return $color;
}


//User Agent 分析
function analyzeUserAgent($userAgent) {
    // 初始化结果数组
    $result = array(
        'browser' => '',
        'version' => '',
        'os' => ''
    );

    // 匹配常见浏览器
    $browserRegexes = array(
        '/msie/i'      => 'IE',
        '/firefox/i'   => 'Firefox',
        '/safari/i'    => 'Safari',
        '/chrome/i'    => 'Chrome',
        '/edge/i'      => 'Edge',
        '/opera/i'     => 'Opera',
        '/netscape/i'  => 'Netscape',
        '/maxthon/i'   => 'Maxthon',
        '/konqueror/i' => 'Konqueror',
        '/mobile/i'    => 'Mobile Browser'
    );

    // 匹配常见操作系统
    $osRegexes = array(
        '/windows/i'             => 'Windows',
        '/macintosh|mac os x/i'  => 'Mac OS X',
        '/mac_powerpc/i'         => 'Mac OS 9',
        '/linux/i'               => 'Linux',
        '/ubuntu/i'              => 'Ubuntu',
        '/iphone/i'              => 'iPhone',
        '/ipod/i'                => 'iPod',
        '/ipad/i'                => 'iPad',
        '/android/i'             => 'Android',
        '/blackberry/i'          => 'BlackBerry',
        '/webos/i'               => 'Mobile'
    );

    // 分析浏览器
    foreach ($browserRegexes as $regex => $browser) {
        if (preg_match($regex, $userAgent)) {
            $result['browser'] = $browser;
            // break;
        }
    }

    // 分析操作系统
    foreach ($osRegexes as $regex => $os) {
        if (preg_match($regex, $userAgent)) {
            $result['os'] = $os;
            // break;
        }
    }

    // 提取浏览器版本号
    if ($result['browser']) {
        $versionRegex = '/' . preg_quote($result['browser'], '/') . '\/([\d\w\.]+)/i';
        preg_match($versionRegex, $userAgent, $matches);
        if (isset($matches[1])) {
            $result['version'] = $matches[1];
        }
    }

    return $result;
}



//获取响应参数
function get_param($key, $default = '', $method = 'post') {
    switch ($method) {
    case 'post':
        return (isset($_POST[$key])) ? $_POST[$key] : $default;
        break;
    case 'get':
        return (isset($_GET[$key])) ? $_GET[$key] : $default;
        break;
    case 'request':
        return (isset($_REQUEST[$key])) ? $_REQUEST[$key] : $default;
        break;
    default:
        return null;
        break;
    }
}

/**
 * 获取今天开始结束时间戳
 * @Author Dadong2g
 * @date   2023-03-05
 * @return [type]
 */
function get_today_time_range() {
    $timezone_object = wp_timezone();
    // 获取今天开始和结束时间的DateTime对象
    $today_start = new DateTime('today', $timezone_object);
    $today_end = clone $today_start;
    $today_end->modify('+1 day');

    // 转换为时间戳
    $today_start_timestamp = $today_start->getTimestamp();
    $today_end_timestamp = $today_end->getTimestamp();


    return array(
        'start' => $today_start->getTimestamp(),
        'end'   => $today_end->getTimestamp(),
    );
}

//获取主题目录地址
function zb_theme_content_url($dir = '') {
    //是否多域名支持
    $content_url = get_template_directory_uri();
    $home_url    = home_url();
    if (strpos($content_url, $home_url) !== false) {
        return $content_url . $dir;
    }
    return $home_url . $content_url . $dir;
}

// 根据字符串搜索用户id 用于搜索
function get_user_id_from_str($string) {
    $string = trim($string);

    if (is_email($string) && $user = get_user_by('email', $string)) {
        return $user->ID;
    }
    if (is_numeric($string) && $user = get_user_by('id', absint($string))) {
        return $user->ID;
    }
    if (is_string($string) && $user = get_user_by('login', $string)) {
        return $user->ID; 
    }
    return 0;
}




/**
 * 时间戳
 * @Author Dadong2g
 * @date   2022-01-06
 * @return [type]
 */
function zb_meta_datetime() {
    
    $time = get_the_time('U');
    $time_string = sprintf(
        '<time class="pub-date" datetime="%1$s">%2$s</time>',
        esc_attr(get_the_date(DATE_W3C)),
        esc_html(human_time_diff($time, current_time('timestamp')) . __('前', 'ripro'))
    );

    if (false) {
        // 显示最近修改时间
        $modified_time = get_the_modified_time('U');
        if ($time != $modified_time) {
            $time_string .= sprintf(
                '<time class="mod-date" datetime="%1$s">%2$s</time>',
                esc_attr(get_the_modified_date(DATE_W3C)),
                esc_html(human_time_diff($modified_time, current_time('timestamp')) . __('前', 'ripro'))
            );
        }
    }
    
    echo $time_string;
}

/**
 * 作者信息
 * @Author Dadong2g
 * @date   2023-04-19
 * @return [type]
 */
function zb_meta_by() {
    printf(
        '<a class=\'stretched-link text-reset btn-link\' href=\'%s\'>%s</a>',
        esc_url(get_author_posts_url(get_the_author_meta('ID'))),
        esc_html(get_the_author())
    );
}


/**
 * 分类信息
 * @Author Dadong2g
 * @date   2023-04-19
 * @param  integer    $num [description]
 * @return [type]
 */
function zb_meta_category($num = 2) {
    $categories = get_the_category();
    $separator = ' ';
    $output = '';
    if ($categories) {
        foreach ($categories as $key => $category) {
            if ($key == $num) {
                break;
            }
            $output .= '<a href="' . esc_url(get_category_link($category->term_id)) . '">' . esc_html($category->name) . '</a>' . $separator;
        }
        echo trim($output, $separator);
    }
}

/**
 * 摘要
 * @Author Dadong2g
 * @date   2022-01-06
 * @param  string     $limit [description]
 * @return [type]
 */
add_filter('excerpt_more', function () {
    return '';
});

function zb_get_post_excerpt($limit = '46') {
    $excerpt = get_the_excerpt();
    if (empty($excerpt)) {
        $excerpt = get_the_content();
    }

    return wp_trim_words(strip_shortcodes($excerpt), $limit, '...');
}

/**
 * 默认头像
 * @Author Dadong2g
 * @date   2023-02-13
 * @return [type]
 */
function get_default_avatar_src() {
    return get_template_directory_uri() . '/assets/img/avatar.png';
}




/**
 * 默认缩略图
 * @Author Dadong2g
 * @date   2023-09-18
 * @return [type]
 */
function get_default_thumbnail_src() {
    global $post;
    $default = _xin('default_thumb') ? _xin('default_thumb') : get_template_directory_uri() . '/assets/img/thumb.jpg';
    $rand_gallery = _xin('rand_default_thumb', '');
    $gallery_ids  = explode(',', $rand_gallery);
    if (!empty($rand_gallery) && !empty($gallery_ids)) {
        $gallery_count = count($gallery_ids);
        $iv            = intval(substr($post->ID, -1));

        if ( !isset($gallery_ids[$iv]) ) {
            $iv = mt_rand(0, $gallery_count-1);
        }
        
        if ($_thum = wp_get_attachment_image_src($gallery_ids[$iv], 'thumbnail')) {
            $thum = $_thum;
        } else {
            $thum = wp_get_attachment_image_src($gallery_ids[$iv], 'full');
        }
        if (!empty($thum[0])) {
            return $thum[0];
        }
    }
    return $default;
}


function get_default_lazy_img_src() {
    return _xin('default_lazy_thumb') ? _xin('default_lazy_thumb') : '';
}



function zb_get_thumbnail_size_type(){
    $options = array(
        'bg-cover',
        'bg-auto',
        'bg-contain',
    );
    $opt = _xin('site_thumb_size_type','bg-cover');

    if (!in_array($opt, $options)) {
        $opt = $options[0];
    }
    return $opt;
}

function zb_get_thumbnail_fit_type(){
    $options = array(
        'bg-left-top',
        'bg-right-top',
        'bg-center-top',
        'bg-center',
        'bg-center-bottom',
        'bg-left-bottom',
        'bg-right-bottom',
    );
    $opt = _xin('site_thumb_fit_type','bg-center');

    if (!in_array($opt, $options)) {
        $opt = $options[0];
    }
    return $opt;
}

/**
 * 获取缩略图地址
 * @Author Dadong2g
 * @date   2023-04-19
 * @param  [type]     $post [description]
 * @param  string     $size [description]
 * @return [type]
 */
function zb_get_thumbnail_url($post = null, $size = 'thumbnail') {

    if (empty($post)) {
        global $post;
    } else {
        $post = get_post($post);
    }

    if (!$post instanceof WP_Post) {
        return get_default_thumbnail_src();
    }

    if (has_post_thumbnail($post)) {
        return get_the_post_thumbnail_url($post, $size);
    } elseif (_xin('is_post_one_thumbnail', true) && !empty($post->post_content)) {
        // Automatically get the first image in the post content
        ob_start();
        ob_end_clean();
        preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        if (!empty($matches[1][0])) {
            return $matches[1][0];
        }
    }

    return get_default_thumbnail_src();
}


//获取媒体预览地址
function zb_get_media_preview_url($post = null){
    if (empty($post)) {
        global $post;
    } else {
        $post = get_post($post);
    }

    if (!$post instanceof WP_Post) {
        return '';
    }

    $url = get_post_meta($post->ID, 'thumb_video_src', true);

    if ( empty($url) ) {
        return '';
    }

    return $url;

}



/**
 * 获取缩略图
 * @Author Dadong2g
 * @date   2022-01-06
 * @param  string     $class [description]
 * @return [type]
 */
function zb_the_thumbnail($post = null, $class = 'thumb lazy', $size = 'thumbnail') {
    if (empty($post)) {
        global $post;
    }

    if (is_numeric($post)) {
        $post = get_post($post);
    }

    echo get_the_post_thumbnail($post->ID, $size, array('class' => $class, 'alt' => the_title_attribute(array('echo' => false))));

}





/**
 * 自定义导航
 * @Author Dadong2g
 * @date   2022-12-02
 * @param  integer    $pagenum       [当前页面]
 * @param  integer    $max_num_pages [MAX数量]
 * @return [type]
 */
function zb_custom_pagination($pagenum = 0, $max_num_pages = 0) {

    $page_links = paginate_links(array(
        'base'      => add_query_arg('page', '%#%'),
        'format'    => '?page=%#%',
        'prev_text' => __('<i class="fas fa-angle-left me-1"></i>上一页', 'ripro'),
        'next_text' => __('下一页<i class="fas fa-angle-right ms-1"></i>', 'ripro'),
        'total'     => intval($max_num_pages),
        'current'   => intval($pagenum),
        'show_all'   => false,
    ));

    // zb_dump($page_links);

    if ($page_links) {
        echo '<nav class="custom-nav mt-3 mt-md-4"><ul class="pagination d-flex justify-content-center flex-wrap"><span class="disabled">'.__('分页', 'ripro').'</span>' . $page_links . '</ul></nav>';
    }

}



/**
 * 判断邮件服务是否开启
 * @Author Dadong2g
 * @date   2022-11-27
 * @param  string     $role [description]
 * @param  [type]     $key  [description]
 * @return [type]
 */
function site_push_server($role, $key) {
    switch ($role) {
    case 'admin':
        $opt_key = 'site_admin_push_server';
        break;
    case 'user':
        $opt_key = 'site_user_push_server';
        break;
    default:
        $opt_key = 'null';
        break;
    }
    $data = _xin($opt_key);
    if (empty($data) || !is_array($data)) {
        return false;
    }
    if (!in_array($key, $data)) {
        return false;
    }
    return true;
}

/**
 * 链接新窗口打开
 * @Author   Dadong2g
 * @DateTime 2021-09-13T20:47:01+0800
 * @return   [type]                   [description]
 */
function get_target_blank() {
    return  '_blank';
}

/**
 * 获取当前页面URL
 * @Author Dadong2g
 * @date   2022-11-27
 * @return [type]
 */
if (!function_exists('get_current_url')) {
    function get_current_url() {
        $current_url = home_url(add_query_arg(array()));
        return esc_url($current_url);
    }
}

/**
 * 获取二维码地址
 * @Author Dadong2g
 * @date   2022-11-28
 * @param  [type]     $text [description]
 * @return [type]
 */
function get_qrcode_url($text) {
    $api_url = get_template_directory_uri() . '/inc/plugins/qrcode/qrcode.php?data=';
    return $api_url . $text;
}

//是否开启图片验证码功能【待定】
function is_site_img_captcha() {
    return !empty(_xin('is_site_img_captcha', 0));
}

//是否开启邮件验证码功能
function is_site_mail_captcha() {
    return !empty(_xin('is_site_mail_captcha', 0));
}


/**
 * 发送邮箱验证码
 * @Author Dadong2g
 * @date   2023-12-10
 * @param  [type]     $emali [description]
 * @return [type]
 */
function send_mail_captcha_code($emali) {
    $originalcode = '0,1,2,3,4,5,6,7,8,9';
    $originalcode = explode(',', $originalcode);
    $countdistrub = 10;
    $_dscode      = "";
    $counts       = 6;
    for ($j = 0; $j < $counts; $j++) {
        $dscode = $originalcode[rand(0, $countdistrub - 1)];
        $_dscode .= $dscode;
    }

    ZB_Cookie::set('mail_captcha_code', ZB_Code::enstr($_dscode));

    return wp_mail($emali, __('验证码','ripro'), __('验证码：','business') . $_dscode);

}


/**
 * 验证码邮箱验证码
 * @Author Dadong2g
 * @date   2023-12-10
 * @param  string     $string [description]
 * @return [type]
 */
function mail_captcha_verify($string = '') {
    $cache = ZB_Cookie::get('mail_captcha_code');
    $cache = ZB_Code::destr($cache);
    // ZB_Cookie::set('mail_captcha_code', '');
    if (empty($cache) || empty($string) || $cache != $string) {
        return false;
    }
    return true;
}



/**
 * 获取图片验证码
 * @Author Dadong2g
 * @date   2022-04-12
 * @return [type]
 */
function get_img_captcha() {
    $builder = new Gregwar\Captcha\CaptchaBuilder(4);
    $builder->build();
    $cache = $builder->getPhrase();
    ZB_Cookie::set('img_captcha_code', ZB_Code::enstr($cache));
    return $builder->inline();
}

function is_img_captcha($string = '') {
    $cache = ZB_Cookie::get('img_captcha_code');
    $cache = ZB_Code::destr($cache);
    // Checking that the posted phrase match the phrase stored in the session
    $is_captcha = Gregwar\Captcha\PhraseBuilder::comparePhrases($cache, $string);

    ZB_Cookie::set('img_captcha_code', '');
    if (empty($cache) || empty($string)) {
        return false;
    }
    return (bool) $is_captcha;
}

/**
 * //识别视频格式
 * @Author Dadong2g
 * @date   2023-06-05
 * @param  [type]     $video_url [description]
 * @return [type]
 */

function zb_get_video_source_types($video_url){
    if (preg_match('/\.(mp4|webm|ogg|m3u8|mpd|mp3|weba|wav|aac)(?:\?.*)?$/i', $video_url, $matches)) {
        $extension = strtolower($matches[1]);
    } else {
        $extension = 'none';
    }

    $sourceTypes = [
        'mp4' =>'video/mp4',
        'webm' =>'video/webm',
        'ogg' =>'video/ogg',
        'm3u8' =>'application/x-mpegURL',
        'mpd' =>'application/dash+xml',
        'mp3' =>'audio/mpeg',
        'wav' =>'audio/wav',
        'aac' =>'audio/aac',
        'weba' =>'audio/webm',
        'none' =>'',
    ];

    return $sourceTypes[$extension];
}



/**
 * 移除 URL 中的分页路由
 * @Author Dadong2g
 * @date   2023-06-09
 * @param  [type]     $url [description]
 * @return [type]
 */
function remove_pagination_route($url) {

  // 解析 URL，获取路径和查询参数
  $parts = parse_url($url);
  
  if (!is_array($parts)) {
    return $url;
  }

  $path = isset($parts['path']) ? $parts['path'] : '';
  $queryString = isset($parts['query']) ? $parts['query'] : '';

  if (empty($path)) {
    return $url;
  }

  // 移除分页路由（例如 /page/2）
  $pathWithoutPage = preg_replace('/\/page\/\d+/', '', $path);

  // 重新构造 URL
  $newUrl = '';
  if (isset($parts['scheme'])) {
    $newUrl .= sprintf('%s://', $parts['scheme']);
  }
  if (isset($parts['host'])) {
    $newUrl .= $parts['host'];
  }
  $newUrl .= $pathWithoutPage;
  if (!empty($queryString)) {
    $newUrl .= sprintf('?%s', $queryString);
  }

  return $newUrl;
}

